// +----------------------------------------------------------------------
// | CmsWing [ 网站内容管理框架 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2115 http://www.cmswing.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: arterli <arterli@qq.com>
// +----------------------------------------------------------------------
module.exports = class extends think.cmswing.center {
  /**
     * index action
     * @return {Promise} []
     */
  async indexAction() {
    // let p = this.get();
    // return this.body="dfdfdfd";
    // let ss = think.service("geetest");
    // let sss = new ss();

    // console.log(this.config("view").nunjucks.extname);
    // auto render template file index_index.html
    this.meta_title = '首页';// 标题1
    this.keywords = this.config('setup.WEB_SITE_KEYWORD') ? this.config('setup.WEB_SITE_KEYWORD') : '';// seo关键词
    this.description = this.config('setup.WEB_SITE_DESCRIPTION') ? this.config('setup.WEB_SITE_DESCRIPTION') : '';// seo描述
    this.active = ['/', '/index', '/index.html'];
    // 首页内容钩子
    await this.hook('hometitle');
    await this.hook('homelist');
    // 右边的钩子

    await this.hook('homeright');
    // debugger;
    // 判断浏览客户端
    if (this.isMobile) {
      const map = {
        'pid': 0,
        'status': 1
      };
      // 排序
      const o = {};
      let order = this.get('order') || 100;
      // console.log(order);
      order = Number(order);
      switch (order) {
        case 1:
          o.update_time = 'ASC';
          break;
        case 2:
          o.view = 'DESC';
          break;
        case 3:
          o.view = 'ASC';
          break;
        default:
          o.update_time = 'DESC';
      }

      this.assign('order', order);
      const data = await this.model('document').where(map).page(this.get('page'), 10).order(o).countSelect();
      this.assign('list', data);
      // console.log(data);
      if (this.isAjax('get')) {
        for (const v of data.data) {
          if (!think.isEmpty(v.pics)) {
            const arr = [];
            for (const i of v.pics.split(',')) {
              arr.push(await get_pic(i, 1, 300, 300));
            }
            v.pics = arr;
          }
          if (!think.isEmpty(v.cover_id)) {
            v.cover_id = await get_pic(v.cover_id, 1, 300, 169);
          }
          if (!think.isEmpty(v.price)) {
            if (!think.isEmpty(get_price_format(v.price, 2))) {
              v.price2 = get_price_format(v.price, 2);
            }
            v.price = get_price_format(v.price, 1);
          }
          v.uid = await get_nickname(v.uid);
          v.url = get_url(v.name, v.id);
          v.update_time = this.moment(v.update_time).fromNow();
        }
        return this.json(data);
      }
      return this.display(this.mtpl());
    } else {
      // debugger;
      // console.log(think.datetime(new Date(), "YYYY-MM-DD"));
      await this.hook('homeEnd');

      const spfl = new Array();// 商品分类
      // 原材料分类数据(大类)
      const yclfl = await this.model('category').alias('c').join({
        table: 'category',
        join: 'left',
        as: 'pc',
        on: {'pc.id': 'c.pid'}
      }).field('c.id,c.name,c.title').where({'pc.name': 'price', 'c.status': 1}).select();
      // 原材料分类数据(小类)
      if (!think.isEmpty(yclfl)) {
        for (var i = 0; i < yclfl.length; i++) {
          spfl[i] = yclfl[i];
          const ycl = await this.model('document').field('id,title').where({'category_id': yclfl[i].id, 'status': 1}).select();
          spfl[i].ycl = ycl;
          spfl[i].yclname = yclfl[i].name;

          // 产成品分类数据（大类）
          const ccpfl = await this.model('category').alias('c').join({
            table: 'category',
            join: 'left',
            as: 'pc',
            on: {'pc.id': 'c.pid'}
          }).field('c.id,c.name,c.title').where({'pc.name': 'centershop', 'c.title': yclfl[i].title, 'c.status': 1}).find();

          // 产成品分类数据（小类）
          const ccp = await this.model('document').field('id,title').where({'category_id': ccpfl.id, 'status': 1}).select();

          spfl[i].ccp = ccp;
          spfl[i].ccpname = ccpfl.name;
        }
      }
      // console.log('spfl++++++++++++++++++++++++++++'+JSON.stringify(spfl));
      this.assign('spfl', spfl);

      return this.display();
    }
  }

  async indexNewAction() {
    console.log('进入方法.....');
    this.meta_title = '首页';// 标题1
    this.keywords = this.config('setup.WEB_SITE_KEYWORD') ? this.config('setup.WEB_SITE_KEYWORD') : '';// seo关键词
    this.description = this.config('setup.WEB_SITE_DESCRIPTION') ? this.config('setup.WEB_SITE_DESCRIPTION') : '';// seo描述
    this.active = ['/', '/indexNew', '/indexNew.html'];
    // 首页内容钩子
    await this.hook('hometitle');
    await this.hook('homelist');
    // 右边的钩子
    await this.hook('homeright');
    await this.hook('homeEnd');
    const faburens = await this.model('member').where({groupid: ['=', 12]}).getField('id');
    const data1 = await this.model('gongxufabu').where({faburen: ['IN', faburens], status: 5, mokuaibiaoshi: ['IN', [1, 2]]}).page(this.get('page') || 1, 10).order('id desc').select();
    this.assign('list1', data1);
    const documentCategories = [148, 149, 141, 136];
    const documentCategoriesDate = await this.model('cmswing/category').where({id: ['IN', documentCategories]}).select();
    // const ids = documentCategoriesDate.map(i => {
    //   return i.id;
    // }).filter(i => i != 141);
    const categoryInfo = {

    };
    const subCategoryMap = {

    };
    const categoryData = {

    };
    await Promise.all(documentCategoriesDate.map(async(categoryDate) => {
      categoryInfo[categoryDate.id] = categoryDate;
      const subCategoriesDate = await this.model('category').where({pid: categoryDate.id}).select();
      subCategoryMap[categoryDate.id] = subCategoriesDate.map(i => i.id);
      await Promise.all(subCategoriesDate.map(async(subCategoryDate) => {
        categoryInfo[subCategoryDate.id] = subCategoryDate;
        const data = await this.model('document').where({
          status: 1,
          category_id: subCategoryDate.id
        }).page(1, 5).order('id desc').select();
        categoryData[subCategoryDate.id] = data;
      }));
    }));
    this.assign('categoryInfo', categoryInfo);
    this.assign('subCategoryMap', subCategoryMap);
    this.assign('categoryData', categoryData);

    const typevar = await this.model('typevar').where({optionid: 51}).order('displayorder ASC').find();
    typevar.option = await this.model('typeoption').where({optionid: 51}).find();
    const fengleiRes = await this.model('material').field('id,label,pid').select({where: {status: 1}});
    const fenglei = arr_to_tree(fengleiRes, 0, null, true);
    typevar.rules = fenglei;
    typevar.option.rules = {choices: fengleiRes.reduce((a, c) => { a[c.id] = c.label; return a }, {}) };
    const map = {'1': '/static/assets_new/img/feigang.png', '40': '/static/assets_new/img/FEIYOUSHE.png', '23': '/static/assets_new/img/feisuliao.png', '45': '/static/assets_new/img/feizhi.png', '50': '/static/assets_new/img/feiboli.png'};
    // 广告
    const adlist = await this.model('document').where({position: ['EXP', '&' + (2 + 4 + 8 + 16)], status: 1, category_id: 174}).field('id,title,description,position,cover_id,link_id').select();
    for (let index = 0; index < adlist.length; index++) {
      const item = adlist[index];
      item.cover = await get_cover(item.cover_id, 'path');
    }
    this.assign('adlist', adlist);
    this.assign('typevar', typevar);
    this.assign('map', map);

    return this.display();
  }
};
